package com.beibei.framework.aspect;

import javax.annotation.Resource;
import javax.xml.ws.WebServiceContext;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import com.beibei.file.bean.JdbcFile;
import com.beibei.framework.logger.ILogger;
import com.beibei.framework.logger.LoggerFactory;

/**
 * JDBC执行语句拦截器
 * 
 * @author 309814490@qq.com
 * @since 2014-02-14
 */
@Aspect
public class JdbcAspect extends BaseAspect {
	@Resource
	private WebServiceContext context;

	/**
	 * 获取日志对象
	 */
	protected ILogger getJdbcLog() {
		return LoggerFactory.getJdbcLog();
	}

	@Pointcut("execution(* org.springframework.jdbc.core.JdbcTemplate.*(..))")
	private void pointCutMethod() {
	}

	@Around("pointCutMethod()")
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {

		// 获取JdbcFile对象
		JdbcFile jdbcFile = this.getJdbcFile(pjp.getArgs());
		jdbcFile.setStartTime(System.currentTimeMillis());

		// 调用服务
		Object object = pjp.proceed();

		// 设置服务调用结束时间
		jdbcFile.setEndTime(System.currentTimeMillis());
		getJdbcLog().file(jdbcFile.getValue());

		return object;
	}

	/**
	 * 创建JdbcFile对象
	 * 
	 * @param args
	 * @return
	 */
	private JdbcFile getJdbcFile(Object[] args) {
		JdbcFile jdbcFile = new JdbcFile();

		try {
			jdbcFile.setSql(String.valueOf(args[0])); // 执行SQL
			jdbcFile.setClassName(String.valueOf(args[1])); // 执行类
			jdbcFile.setClientIp(super.getUserIp(context)); // 客户端IP
		} catch (Exception e) {
			getCommonLog().error("getJdbcFile", "error", e);
		}

		return jdbcFile;
	}

}
